package com.sfdcj.se.meta.proc;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;

import com.sfdcj.se.SfdcException;
import com.sfdcj.se.meta.Outcome;
import com.sfdcj.se.meta.field.FieldType;
import com.sfdcj.se.meta.field.FieldTypeBuilder;
import com.sfdcj.se.meta.soap.CustomObjectCreator;
import com.sfdcj.se.meta.soap.MetadataService;
import com.sfdcj.se.util.Utils;
import com.sforce.soap._2006._04.metadata.CustomField;
import com.sforce.soap._2006._04.metadata.CustomObject;

public class SObjectDirectCreateProcessor implements Processor {

	static public String LABEL = "PARAM_LABEL";
	static public String TYPE = "PARAM_TYPE";
	static public String FULLNAME = "PARAM_FULLNAME";
	static public String ATTRS = "PARAM_ATTRS";
	static public String OBJNAME = "PARAM_OBJNAME";
	static public String OBJLABEL = "PARAM_OBJLABEL";
	static public String ORGID = "PARAM_ORGID";
	static public String PASSWD = "PARAM_PASSWD";
	static public String EXISTOBJ = "PARAM_EXISTOBJ";

	static private FieldTypeBuilder builder = new FieldTypeBuilder();

	static String NEXTPAGE = "./meta/fieldxml.jsp";

	public Outcome execute(HttpServletRequest req, HttpServletResponse res)
			throws SfdcException {

		String objname = Utils.getParameter(req, OBJNAME);
		String objlabel = Utils.getParameter(req, OBJLABEL);
		String org = Utils.getParameter(req, ORGID);
		String password = Utils.getParameter(req, PASSWD);
		String add2existingObj = Utils.getParameter(req, EXISTOBJ);
		System.out.println("orgid: " + org);

		final CustomObject obj = CustomObjectCreator.createCustomObject(
				objlabel, objname);

		MetadataService soap = new MetadataService();

		soap.login(org, password);
		if (!"on".equals(add2existingObj))
			soap.createMetadataObject(obj);

		List<String> typeKeys = Utils.getParamsWithKeywords(req, TYPE);
		List<CustomField> fields = new ArrayList<CustomField>();
		for (String typeKey : typeKeys) {
			String index = typeKey.substring(TYPE.length(), typeKey.length());
			String label = Utils.getParameter(req, LABEL + index);
			String fullname = Utils.getParameter(req, FULLNAME + index);

			if (label == null || fullname == null)
				continue;

			String attrs = Utils.getParameter(req, ATTRS + index);
			String type = Utils.getParameter(req, typeKey);

			FieldType field = builder.create(objname, type, label, fullname,
					attrs);
			fields.add(field.toCustomField());
		}

		CustomField[] cfields = ((CustomField[]) fields
				.toArray(new CustomField[fields.size()]));
		soap.createMetadataObjects(cfields);

		Outcome outcome = new Outcome();
		outcome.returnJsp = NEXTPAGE;
		outcome.obj = "カスタムオブジェクトが作成されました";
		return outcome;
	}
}
